package com.qianchang.microfinance.global;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.support.multidex.MultiDexApplication;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.dm.library.http.DMHostnameVerifier;
import com.dm.library.http.DMX509TrustManager;
import com.dm.library.http.TokenManager;
import com.dm.library.log.transaction.log.manager.LogManager;
import com.dm.library.utils.DMCache;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.StringUtils;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.dao.DaoMaster;
import com.qianchang.microfinance.dao.DaoSession;
import com.qianchang.microfinance.dao.SQLdm;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.GetJsonDataUtil;
import com.qianchang.microfinance.utils.YMDeviceInfoUtils;
import com.rong360.app.crawler.CrawlerManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import cn.tsign.esign.tsignsdk2.TESeal;
import cn.tsign.esign.tsignsdk2.enums.EnumServer;
import okhttp3.OkHttpClient;

/**
 * 版    权:  深圳市迪蒙网络科技有限公司
 * 描    述:  <描述>
 * 修 改 人:  jiaohongyun
 * 修改时间:  2016/8/24
 */
public class DMApplication extends MultiDexApplication {
    /**
     * 应用实例
     */
    private static DMApplication instance;
    private UserLoginInfo mUserLoginInfo;

    private String versionName;

    private String imei;
    private DaoSession daoSession;

    private static final String TAG = DMApplication.class.getName();
    private Handler handler;

    /**
     * 返回 application对象
     *
     * @return
     */
    public static DMApplication getInstance() {
        return instance;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        configHttps();
        // 记录日志 LogUtils类DEBUG、CRASH_SAVE_2_FILE开启或关闭
        LogManager.getManager(getApplicationContext()).registerCrashHandler();
        initLog();
        initOtherData();

        CrawlerManager.initSDK(this);           //初始化融360抓取

        initUpush();                //第一步初始化友盟推送SDK，第二步在 DmBaseActivity 的onCreate 方法中初始化 PushAgent.getInstance(getApplicationContext()).onAppStart();

//        getmDeviceInfo();           //友盟集成测试使用

    }

    private void getmDeviceInfo() {
        String str = YMDeviceInfoUtils.getDeviceInfo(getApplicationContext());
        Log.e(TAG, "============================================================== getDeviceInfo: " + str);

    }

    private void initOtherData() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                GetJsonDataUtil.newInstance();
            }
        }.start();

        //易签宝初始化
        //正式环境
//        TESeal.getInstance().init(getInstance(), "1111564519", "289173253231a2b32a6e266a24e5a6e8", EnumServer.simulation);

        TESeal.getInstance().init(getInstance(), "1111563517", "95439b0863c241c63a861b87d1e647b7", EnumServer.simulation);

        //模拟环境
//        TESeal.getInstance().init(getApplicationContext(), "1111563562", "612c09869b978d3f642242c79439aaaa", EnumServer.simulation);  //模拟环境
    }

    /**
     * 初始化日志
     */
    private void initLog() {
        DMLog.Builder builder = new DMLog.Builder(this)
                .setLogSwitch(true)// 设置log总开关，包括输出到控制台和文件，默认开
                .setBorderSwitch(true)// 输出日志是否带边框开关，默认开
                //.setConsoleSwitch(true)// 设置是否输出到控制台开关，默认开
                //.setLogHeadSwitch(true)// 设置log头信息开关，默认为开
                // 当全局标签不为空时，我们输出的log全部为该tag，
                // 为空时，如果传入的tag为空那就显示类名，否则显示tag
                //.setGlobalTag("")// 设置log全局标签，默认为空
                //.setDir("")// 当自定义路径为空时，写入应用的/cache/log/目录中
                //.setLog2FileSwitch(false)// 打印log时是否存到文件的开关，默认关
                //.setConsoleFilter(DMLog.V)// log的控制台过滤器，和logcat过滤器同理，默认Verbose
                .setFileFilter(DMLog.V);// log文件过滤器，和logcat过滤器同理，默认Verbose
        DMLog.d(builder.toString());
    }

    private void configHttps() {
        // 对OkHttpClient
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60000L, TimeUnit.MILLISECONDS)
                .readTimeout(60000L, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggerInterceptor("TAG"))
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager).build();
        OkHttpUtils.initClient(okHttpClient);

        // 对HttpsURLConnection
        try {
            // 忽略证书
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new DMX509TrustManager()}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new DMHostnameVerifier());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    }

    /***
     * 获取缓存用户信息
     *
     * @return
     */
    public UserLoginInfo getmUserLoginInfo() {
        if (mUserLoginInfo == null) {
            //读取缓存中的用户信息
            DMCache dmCache = DMCache.get(this);
            mUserLoginInfo = (UserLoginInfo) dmCache.getAsObject(DMConstant.DMCACHE_STRING.DM_LOGIN_USER);
        }
        return mUserLoginInfo;
    }

    /**
     * 保存用户登录信息
     * @param userLoginInfo
     */
    public void setUserLoginInfo(UserLoginInfo userLoginInfo) {
        if (userLoginInfo != null) {
            //保存登录信息到缓存，无过期，退出登录或token过期时remove
            DMCache dmCache = DMCache.get(this);
            dmCache.put(DMConstant.DMCACHE_STRING.DM_LOGIN_USER, userLoginInfo);
        } else {  //如果userLoginInfo为空，则表示退出登录了
            mUserLoginInfo = null;
            DMCache dmCache = DMCache.get(this);
            dmCache.remove(DMConstant.DMCACHE_STRING.DM_LOGIN_USER);
            TokenManager.getInstance().removeToken(this);
        }
    }

    public String getVersion() {
        if (StringUtils.isEmptyOrNull(versionName)) {
            try {
                PackageManager manager = this.getPackageManager();
                PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
                versionName = info.versionName;
                return versionName;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return versionName;
    }

    @SuppressLint("MissingPermission")
    public String getImei() {
        if (StringUtils.isEmptyOrNull(imei)) {
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();
        }
        return imei;
    }

    /**
     * 删除保存的用户信息
     */
    public void removeLoginInfo() {
        DMCache dmCache = DMCache.get(this);
        dmCache.remove(DMConstant.DMCACHE_STRING.DM_LOGIN_USER);
        this.mUserLoginInfo = null;
    }

    /**
     * 是否已经登录
     *
     * @return
     */
    public boolean isLogin() {
        return getmUserLoginInfo() != null;
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    private void configDataBase() {
        SQLdm s = new SQLdm();
        try {
            s.copyDataBase(this, "IndonesiaFinance.db");
            SQLiteDatabase sqLiteDatabase = s.openDatabase(this, "IndonesiaFinance.db");
            if (null != sqLiteDatabase) {
                DaoMaster daoMaster = new DaoMaster(sqLiteDatabase);
                daoSession = daoMaster.newSession();
            } else {
                daoSession = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        DaoSession daoSession = daoMaster.newSession();
//        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "IndonesiaFinance.db");
//        Database writableDb = devOpenHelper.getWritableDb();
//        DaoMaster master = new DaoMaster(writableDb);
    }


    public static final String UPDATE_STATUS_ACTION = "com.qianchang.microfinance.action.UPDATE_STATUS";
    //初始化友盟推送
    private void initUpush() {

        UMConfigure.setLogEnabled(true);

        String appkey = "5b067e9fa40fa326c80000e9";     //友盟 APPKey
        String umengMessageSecret = "617387afadbfffd7261b9ef21fe68dd7";         //友盟推送 Umeng Message Secret
        String channel_id = getResources().getString(R.string.channel_id);
        UMConfigure.init(this, appkey,channel_id, UMConfigure.DEVICE_TYPE_PHONE, umengMessageSecret);

        // 友盟统计设置为U-APP场景
        MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL);

        PushAgent mPushAgent = PushAgent.getInstance(this);
        handler = new Handler(getMainLooper());


        //sdk开启通知声音
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        // sdk关闭通知声音
        // mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        // 通知声音由服务端控制
        // mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);

        // mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        // mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);

        UmengMessageHandler messageHandler = new UmengMessageHandler() {

            /**
             * 通知的回调方法（通知送达时会回调）
             */
            @Override
            public void dealWithNotificationMessage(Context context, UMessage msg) {
                //调用super，会展示通知，不调用super，则不展示通知。
                super.dealWithNotificationMessage(context, msg);
            }

            /**
             * 自定义消息的回调方法
             */
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {

                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        // 对自定义消息的处理方式，点击或者忽略
                        boolean isClickOrDismissed = true;
                        if (isClickOrDismissed) {
                            //自定义消息的点击统计
                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
                        } else {
                            //自定义消息的忽略统计
                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
                        }
                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                    }
                });
            }

            /**
             * 自定义通知栏样式的回调方法
             */
            @Override
            public Notification getNotification(Context context, UMessage msg) {
                switch (msg.builder_id) {
                    case 1:
                        Notification.Builder builder = new Notification.Builder(context);
                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(),
                                R.layout.notification_view);
                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(R.id.notification_small_icon,
                                getSmallIconId(context, msg));
                        builder.setContent(myNotificationView)
                                .setSmallIcon(getSmallIconId(context, msg))
                                .setTicker(msg.ticker)
                                .setAutoCancel(true);

                        return builder.getNotification();
                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        /**
         * 自定义行为的回调处理，参考文档：高级功能-通知的展示及提醒-自定义通知打开动作
         * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {

            @Override
            public void launchApp(Context context, UMessage msg) {
                super.launchApp(context, msg);
            }

            @Override
            public void openUrl(Context context, UMessage msg) {
                super.openUrl(context, msg);
            }

            @Override
            public void openActivity(Context context, UMessage msg) {
                super.openActivity(context, msg);
            }

            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
            }
        };
        //使用自定义的NotificationHandler
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        //注册推送服务 每次调用register都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                Log.i(TAG, "device token: " + deviceToken);
                Log.e(TAG, "============================================================== device token: " + deviceToken);

                TokenManager.getInstance().setDeviceToken(getApplicationContext(),deviceToken);

//                sendBroadcast(new Intent(UPDATE_STATUS_ACTION));
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.i(TAG, "register failed: " + s + " " + s1);
//                sendBroadcast(new Intent(UPDATE_STATUS_ACTION));
            }
        });

        //使用完全自定义处理
        //mPushAgent.setPushIntentServiceClass(UmengNotificationService.class);

        //小米通道
        //MiPushRegistar.register(this, XIAOMI_ID, XIAOMI_KEY);
        //华为通道
        //HuaWeiRegister.register(this);
        //魅族通道
        //MeizuRegister.register(this, MEIZU_APPID, MEIZU_APPKEY);

    }



}
